package cn.klaw.handler;

import com.alibaba.fastjson.JSON;
import cn.klaw.consts.ProjectEventConst;
import cn.klaw.consts.RedisConst;
import cn.klaw.event.ProjectEventSender;
import cn.klaw.module.ProjectEvent;
import cn.klaw.properties.EventProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;

/**
 * 自定义事件发布 Redis渠道
 */
@Slf4j
public class ProjectEventRedisSender implements ProjectEventSender {


    private RedisTemplate redisTemplate;
    private EventProperty eventProperties;

    public ProjectEventRedisSender(RedisTemplate redisTemplate, EventProperty eventProperties) {
        this.redisTemplate = redisTemplate;
        this.eventProperties = eventProperties;
    }

    @Override
    public void send(ProjectEvent event) {
        String channel = event.getChannel();
        // channel 加上指定前缀
        if(Objects.equals(eventProperties.getRedisPublishType(), ProjectEventConst.REDIS_PUBLISH_TYPE_ALL)){
            // 订阅同一个Redis里的所有消息
            channel = ProjectEventConst.DEFAULT_CHANNEL_PREFIX + channel;
        }else{
            // 只订阅当前配置的库索引
            channel = RedisConst.REDIS_EVENT_KEY + ProjectEventConst.DEFAULT_CHANNEL_PREFIX + channel;
        }
        redisTemplate.convertAndSend(channel, event);
        if (log.isDebugEnabled()) {
            log.debug("发送Redis自定义事件: {}", JSON.toJSONString(event));
        }
    }
}
